<?php

class UsersController extends Controller {

	public function init() {
		parent::init();
	}

	/**
	 * Displays the login page
	 */
//	public function actionLogin() {
//		if (!Yii::app()->user->isGuest)
//			Yii::app()->request->redirect(Yii::app()->user->returnUrl);
//		$model = new LoginForm;
//		if (isset($_POST['LoginForm'])) {
//			$model->attributes = $_POST['LoginForm'];
//			if ($model->validate() && $model->login()){
//				if(Yii::app()->user->checkAccess(Users::ROLE_MODER))
//					Yii::app()->controller->redirect($this->createUrl('admin/main/index'));
//				else
//					$this->redirect(Yii::app()->user->returnUrl);
//			}
//				
//		}
//		$this->render('login', array('model' => $model));
//	}
	
	public function actionLogin() {
		$this->layout = '//layouts/login';

		if (!Yii::app()->user->isGuest){
			Yii::app()->request->redirect(Yii::app()->user->returnUrl);
		}

		$model = new Users('login');

		if(Yii::app()->request->isPostRequest) {
			$model->attributes = Yii::app()->request->getPost('Users');

			if ($model->validate()){
				$model->login();
				if(Yii::app()->user->checkAccess(Users::ROLE_MODER)){
					Yii::app()->controller->redirect($this->createUrl('admin/main/index'));
				}else{
					$this->redirect(Yii::app()->user->returnUrl);
				}
			}
		}

		$this->render('login', array('model' => $model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout() {
		Yii::app()->user->logout();

		$this->redirect(Yii::app()->homeUrl);
	}
        
	/**
	 * регістрація
	 */
	public function actionRegister() {
		if (!Yii::app()->user->isGuest){
			Yii::app()->request->redirect($this->createUrl('main/index'));
		}

		$model = new Users('register_users');

		if(Yii::app()->request->isPostRequest) {
			$model->attributes = Yii::app()->request->getPost('Users');

			if ($model->validate()){
			  $date = date('Y-m-d H:i:s');

			  $salt = $model->get_salt();

			  $pass = $model->password;

			  $model->salt = $salt;
			  $model->created = $date;
			  $model->last_visit = $date;
			  $model->role = Users::ROLE_USER;
			  $model->password = $model->get_password_with_salt($pass, $salt);
			  $model->retry_password = $model->get_password_with_salt($pass, $salt);

			  if($model->save()){
				  $model->password = $pass;
				  $model->login();
				  $this->redirect(Yii::app()->user->returnUrl);
			  }
			}
		}

		$model->password = '';
		$model->retry_password = '';
		$this->render('register', array('model' => $model));
	}

}